<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :sm="24" :md="24" :xxl="16">
            <a-form-item label="区域">
              <a-row :gutter="5" type="flex">
                <a-col :span="3">
                  <a-select
                    placeholder="省"
                    v-model="queryParam.provinceCode"
                    @change="e => addressChange(e, 'cityOptions', 'province')"
                  >
                    <a-select-option v-for="item in provinceOptions" :key="item.name" :value="item.code">
                      {{ item.name }}
                    </a-select-option>
                  </a-select>
                </a-col>
                <a-col :span="3">
                  <a-select
                    placeholder="市"
                    v-model="queryParam.cityCode"
                    @change="e => addressChange(e, 'areaOptions', 'city')"
                  >
                    <a-select-option v-for="item in cityOptions" :key="item.name" :value="item.code">
                      {{ item.name }}
                    </a-select-option>
                  </a-select>
                </a-col>
                <a-col :span="3">
                  <a-select
                    placeholder="区"
                    v-model="queryParam.areaCode"
                    @change="e => addressChange(e, 'streetOptions', 'area')"
                  >
                    <a-select-option v-for="item in areaOptions" :key="item.name" :value="item.code">
                      {{ item.name }}
                    </a-select-option>
                  </a-select>
                </a-col>
                <a-col :span="3">
                  <a-select
                    placeholder="街道"
                    v-model="queryParam.streetCode"
                    @change="e => addressChange(e, '', 'street')"
                  >
                    <a-select-option v-for="item in streetOptions" :key="item.name" :value="item.code">
                      {{ item.name }}
                    </a-select-option>
                  </a-select>
                </a-col>
                <a-col :span="4">
                  <a-select
                    placeholder="商家"
                    v-model="queryParam.businessId"
                    @change="e => agentChange(e, 'networkOptions', 'agentCode')"
                  >
                    <a-select-option v-for="item in agentOptions" :key="item.name" :value="item.code">
                      {{ item.name }}
                    </a-select-option>
                  </a-select>
                </a-col>
                <a-col :span="4">
                  <a-select
                    placeholder="网点"
                    v-model="queryParam.networkId"
                    @change="e => agentChange(e, 'deviceOptions', 'networkCode')"
                  >
                    <a-select-option v-for="item in networkOptions" :key="item.name" :value="item.code">
                      {{ item.name }}
                    </a-select-option>
                  </a-select>
                </a-col>
                <a-col :span="4">
                  <a-select placeholder="设备" v-model="queryParam.id">
                    <a-select-option v-for="item in deviceOptions" :key="item.name" :value="item.code">
                      {{ item.name }}
                    </a-select-option>
                  </a-select>
                </a-col>
              </a-row>
            </a-form-item>
          </a-col>
          <a-col :sm="24" :md="12" :xl="8">
            <a-form-item label="设备ID">
              <a-input allowClear placeholder="请输入" v-model="queryParam.deviceId"></a-input>
            </a-form-item>
          </a-col>
          <a-col :sm="24" :md="12" :xl="8">
            <a-form-item label="主板编号">
              <a-input allowClear placeholder="请输入" v-model="queryParam.mainboardId"></a-input>
            </a-form-item>
          </a-col>
          <a-col :sm="24" :md="12" :xl="8">
            <a-form-item label="设备类型">
              <j-dict-select-tag
                allowClear
                v-model="queryParam.deviceType"
                placeholder="请选择"
                dictCode="deviceType"
              />
            </a-form-item>
          </a-col>

          <a-col :sm="24" :md="12" :xl="8" v-if="!isBusiness">
            <a-form-item label="在线状态">
              <j-dict-select-tag
                allowClear
                v-model="queryParam.businessStatus"
                placeholder="请选择"
                dictCode="businessStatus"
              />
            </a-form-item>
          </a-col>

          <template v-if="toggleSearchStatus || isBusiness">
            <a-col :sm="24" :md="12" :xl="8">
              <a-form-item label="设备状态">
                <j-dict-select-tag
                  allowClear
                  v-model="queryParam.equipmentStatus"
                  placeholder="请选择"
                  dictCode="equipmentStatus"
                />
              </a-form-item>
            </a-col>

            <a-col :sm="24" :md="12" :xl="8">
              <a-form-item label="创建时间">
                <a-range-picker allowClear class="per100" v-model="tempTimes" @change="timeChange" />
              </a-form-item>
            </a-col>

            <a-col :sm="24" :md="12" :xl="8" v-if="!isBusiness">
              <a-form-item label="所属公司">
                <a-select allowClear placeholder="请选择" v-model="queryParam.companyId">
                  <a-select-option v-for="item in companyOptions" :key="item.id" :value="item.id">{{
                    item.companyName
                  }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </template>

          <a-col :sm="24" :md="12" :xl="8">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button @click="searchReset()" icon="reload" style="margin-left: 8px">重置</a-button>
              <a @click="handleToggleSearch" style="margin-left: 8px" v-if="!isBusiness">
                {{ toggleSearchStatus ? '收起' : '展开' }}
                <a-icon :type="toggleSearchStatus ? 'up' : 'down'" />
              </a>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <!-- 操作按钮区域 -->
    <div class="table-operator mt10">
      <a-button type="success" icon="plus" v-has="'device:add'" @click="handleAdd()">新增机器</a-button>
      <a-button type="primary" v-has="'device:edit'" @click="showModal('setMeal', 'MealManageRef')"
        >批量修改套餐</a-button
      >
    </div>

    <!-- table区域 -->
    <a-table
      ref="table"
      bordered
      size="middle"
      rowKey="deviceId"
      :columns="columns"
      :dataSource="dataSource"
      :pagination="ipagination"
      :loading="loading"
      :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
      :scroll="{ x: 1200 }"
      @change="handleTableChange"
    >
      <template slot="equipmentStatus" slot-scope="text, record">
        <a-badge status="processing" v-if="text === 0" />
        <a-badge status="success" v-if="text === 1" />
        <a-badge status="error" v-if="text === 2" />
        <a-badge status="default" v-if="text === 3" />
        {{ filterDictText(equipmentStatusOptions, text) }}
      </template>
      <template slot="businessStatus" slot-scope="text, record">
        <a-tag :color="text === '0' ? 'red' : 'green'">{{ filterDictText(businessStatusOptions, text) }}</a-tag>
      </template>
      <span slot="action" slot-scope="text, record">
        <a-button type="cyan" class="mg5" size="small" v-has="'device:edit'" @click="handleUpdate(record.id)">
          编辑
        </a-button>
        <a-button
          type="primary"
          class="mg5"
          size="small"
          v-has="'device:setMeal'"
          @click="showModal(record, 'MealManageRef')"
        >
          套餐
        </a-button>
        <a-button
          type="success"
          class="mg5"
          size="small"
          @click="showModal(record, 'CellManageRef')"
          v-has="'device:edit'"
        >
          格子管理
        </a-button>
        <a-dropdown :trigger="['click']">
          <a-menu slot="overlay">
            <a-menu-item key="2" v-has="'device:stopService'">
              <a-popconfirm placement="topRight" @confirm="stopServce(record)">
                <template slot="title">
                  <h3>系统提示</h3>
                  <p>确认要停止服务吗？</p>
                </template>
                <a-button type="danger" class="mg5" size="small">停止服务</a-button>
              </a-popconfirm>
            </a-menu-item>
            <a-menu-item key="3" v-has="'device:updateApp'">
              <a-popconfirm placement="topRight" @confirm="updateApp(record)">
                <template slot="title">
                  <h3>系统提示</h3>
                  <p>确认要更新APP吗？</p>
                </template>
                <a-button type="orange" class="mg5" size="small">
                  更新APP
                </a-button>
              </a-popconfirm>
            </a-menu-item>
            <a-menu-item key="4" v-has="'device:restart'">
              <a-popconfirm placement="topRight" @confirm="deviceRestart(record)">
                <template slot="title">
                  <h3>系统提示</h3>
                  <p>确认要重启设备吗？</p>
                </template>
                <a-button type="orange" class="mg5" size="small">重启设备</a-button>
              </a-popconfirm>
            </a-menu-item>
            <a-menu-item key="5" v-has="'device:reset'">
              <a-popconfirm placement="topRight" @confirm="showModal(record, 'CheckResetRef')">
                <template slot="title">
                  <h3>系统提示</h3>
                  <p>确认要清除该设备的订单数据吗？</p>
                </template>
                <a-button type="danger" class="mg5" size="small">数据重置</a-button>
              </a-popconfirm>
            </a-menu-item>
            <a-menu-item key="6" v-has="'device:delete'">
              <a-popconfirm placement="topRight" @confirm="deviceDelete(record)">
                <template slot="title">
                  <h3>系统提示</h3>
                  <p>确认要删除该设备吗？</p>
                </template>
                <a-button type="danger" class="mg5" size="small">删除设备</a-button>
              </a-popconfirm>
            </a-menu-item>
          </a-menu>
          <a-button size="small" type="cyan" style="margin-left: 5px"> 更多操作 <a-icon type="down" /> </a-button>
        </a-dropdown>
      </span>
    </a-table>

    <!-- 套餐管理 -->
    <meal-manage ref="MealManageRef"></meal-manage>
    <!-- 格子管理 -->
    <cell-manage ref="CellManageRef" @refresh="loadData()"></cell-manage>
    <!-- 清除数据 -->
    <check-reset ref="CheckResetRef" @ok="loadData()"></check-reset>
    <!-- 新增机器 -->
    <device-add ref="DeviceAddtRef" @ok="loadData()"></device-add>
  </a-card>
</template>

<script>
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import Api from '@/api/DeviceManage/DeviceList'
import CommonApi from '@/api/Common/index'
import { initDictOptions, filterDictText } from '@/components/dict/JDictSelectUtil'
import { getAction, httpAction, deleteAction } from '@/api/manage'
import MealManage from './Modal/MealManage'
import CellManage from './Modal/CellManage'
import CheckReset from './Modal/CheckReset.vue'
import DeviceAdd from '@views/DeviceManage/Modal/DeviceAdd'
import { RoleMixin } from '@/mixins/roleUtil'

export default {
  name: 'DeviceList',
  mixins: [JeecgListMixin, RoleMixin],
  components: { MealManage, CellManage, CheckReset, DeviceAdd },
  data() {
    return {
      filterDictText,
      url: {
        list: Api.list
      },
      columns: [],
      deviceTypeOptions: [],
      equipmentStatusOptions: [],
      businessStatusOptions: [],
      companyOptions: [],
      signalIntensityOptions: [],
      billingMethodOptions: []
    }
  },
  created() {
    this.columns = [
      {
        title: '设备ID',
        dataIndex: 'deviceId',
        width: 90,
        align: 'center',
        sorter: (a, b) => {
          return a.deviceId - b.deviceId
        }
      },
      {
        title: '商家ID',
        dataIndex: 'businessId',
        align: 'center',
        width: 140,
        sorter: true
      },
      {
        title: '商家',
        dataIndex: 'businessName',
        align: 'center',
        width: 140
      },
      {
        title: '型号',
        dataIndex: 'deviceType',
        width: 120,
        align: 'center',
        customRender: (text, record, index) => {
          //字典值替换通用方法
          return filterDictText(this.deviceTypeOptions, text)
        },
        sorter: (a, b) => {
          return a.deviceType - b.deviceType
        }
      },
      {
        title: '计费方式',
        dataIndex: 'billingMethod',
        width: 100,
        align: 'center',
        customRender: (text, record, index) => {
          //字典值替换通用方法
          return filterDictText(this.billingMethodOptions, text)
        },
        sorter: (a, b) => {
          return a.billingMethod - b.billingMethod
        }
      },
      {
        title: '设备别名',
        dataIndex: 'deviceName',
        align: 'center',
        width: 100,
        sorter: (a, b) => {
          return a.deviceName - b.deviceName
        }
      },
      {
        title: '主板编号',
        dataIndex: 'mainboardId',
        align: 'center',
        width: 100,
        sorter: (a, b) => {
          return a.mainboardId - b.mainboardId
        }
      },
      {
        title: '格子个数',
        dataIndex: 'cellNum',
        align: 'center',
        width: 100,
        sorter: (a, b) => {
          return a.cellNum - b.cellNum
        }
      },
      {
        title: '网点',
        dataIndex: 'networkName',
        align: 'center',
        width: 140,
        sorter: (a, b) => {
          return a.networkName - b.networkName
        }
      },
      {
        title: '区域',
        dataIndex: 'provinceCn',
        align: 'center',
        width: 300,
        customRender: (text, record, index) => {
          return ['provinceCn', 'cityCn', 'areaCn', 'streetCn']
            .filter(field => record[field])
            .map(field => record[field])
            .reduce((pre, cur) => pre + cur, '')
        },
        sorter: (a, b) => {
          return a.provinceCn - b.provinceCn
        }
      },
      {
        title: '设备状态',
        dataIndex: 'equipmentStatus',
        width: 100,
        align: 'center',
        scopedSlots: { customRender: 'equipmentStatus' },
        sorter: (a, b) => {
          return a.equipmentStatus - b.equipmentStatus
        }
      },
      {
        title: '创建时间',
        dataIndex: 'createTime',
        align: 'center',
        width: 150,
        sorter: (a, b) => {
          return a.createTime - b.createTime
        }
      },
      {
        title: '在线状态',
        dataIndex: 'businessStatus',
        align: 'center',
        fixed: 'right',
        width: 80,
        scopedSlots: { customRender: 'businessStatus' },
        sorter: (a, b) => {
          return a.businessStatus - b.businessStatus
        }
      },
      {
        title: '版本号',
        dataIndex: 'versionId',
        fixed: 'right',
        align: 'center',
        width: 100,
        sorter: (a, b) => {
          return a.versionId - b.versionId
        }
      },
      {
        title: '操作',
        dataIndex: 'action',
        scopedSlots: { customRender: 'action' },
        fixed: 'right',
        width: 320
      }
    ]
    this.getAddress('provinceOptions')
    this.initDictConfig()
    this.getCompanyList()
  },
  methods: {
    // 初始化数据字典
    initDictConfig() {
      //初始化字典 - 设备类型
      initDictOptions('deviceType').then(res => {
        if (res.success) {
          this.deviceTypeOptions = res.result
        }
      })
      //初始化字典 - 设备状态
      initDictOptions('equipmentStatus').then(res => {
        if (res.success) {
          this.equipmentStatusOptions = res.result
        }
      })
      //初始化字典 - 在线状态
      initDictOptions('businessStatus').then(res => {
        if (res.success) {
          this.businessStatusOptions = res.result
        }
      })
      //初始化字典 - 信号强度
      initDictOptions('signalIntensity').then(res => {
        if (res.success) {
          this.signalIntensityOptions = res.result
        }
      })
      //初始化字典 - 计费方式
      initDictOptions('billingMethod').then(res => {
        if (res.success) {
          this.billingMethodOptions = res.result
        }
      })
    },

    handleAdd() {
      this.$refs.DeviceAddtRef.showModal()
    },

    // 新增机器
    handleUpdate(id) {
      const key = id ? id : 'add'
      this.$router.push(`/deviceManage/deviceUpdate/${key}`)
    },

    // 时间改变
    timeChange(e, arr) {
      if (arr[0]) {
        this.queryParam.startTime = arr[0]
        this.queryParam.endTime = arr[1]
      } else {
        this.queryParam.startTime = undefined
        this.queryParam.endTime = undefined
      }
    },

    // 更新APP
    getCompanyList() {
      getAction(CommonApi.companyList).then(res => {
        if (res.code === 200) {
          this.companyOptions = res.result
        } else {
          this.$message.error(res.message)
        }
      })
    },

    // 展示弹窗
    showModal(record, name) {
      if (record === 'setMeal') {
        // 批量修改套餐
        if (!this.selectedRowKeys.length) {
          this.$message.error('请选择一个设备')
          return
        } else {
          this.$refs[name].showModal(record, this.selectedRowKeys)
        }
      } else {
        this.$refs[name].showModal(record)
      }
    },

    // 停止服务
    stopServce(record) {
      const data = {
        id: record.id,
        equipmentStatus: 2
      }
      const url = Api.edit
      const method = 'put'
      this.loading = true
      httpAction(url, data, method)
        .then(res => {
          if (res.code === 200) {
            this.$message.success('停止服务成功')
            this.loadData()
          } else {
            this.$message.error(res.message)
          }
        })
        .finally(() => {
          this.loading = false
        })
    },

    // 更新APP
    updateApp(record) {
      getAction(Api.updateApp, { id: record.deviceId }).then(res => {
        if (res.code === 200) {
          this.$message.success('更新成功')
          this.loadData()
        } else {
          this.$message.error(res.message)
        }
      })
    },

    // 重启设备
    deviceRestart(record) {
      getAction(Api.restart, { id: record.deviceId }).then(res => {
        if (res.code === 200) {
          this.$message.success('重启成功')
          this.loadData()
        } else {
          this.$message.error(res.message)
        }
      })
    },

    // 删除设备
    deviceDelete({ id }) {
      deleteAction(Api.delete, { id }).then(res => {
        if (res.code === 200) {
          this.$message.success('删除成功')
          this.loadData()
        } else {
          this.$message.error(res.message)
        }
      })
    }
  }
}
</script>

<style scoped>
.mg5 {
  margin: 5px;
}
</style>

